//
//  SISSPriceTrendChart.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/9/10.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSPriceTrendChart.h"
#import "SISSTitleView.h"
#import <Charts/Charts-Swift.h>
#import "SISSDateValueFormatter.h"

@interface SISSPriceTrendChart ()
/// titleView
@property (weak, nonatomic) SISSTitleView *titleView;
/// leftUnitLabel
@property (weak, nonatomic) UILabel *leftUnitLabel;
/// rightUnitLabel
@property (weak, nonatomic) UILabel *rightUnitLabel;
/// lineChartView
@property (strong, nonatomic) LineChartView *lineChartView;
/// bottomTag
@property (weak, nonatomic) UIView *leftBottomView;
@property (weak, nonatomic) UILabel *leftBottomLabel;
@property (weak, nonatomic) UIView *rightBottomView;
@property (weak, nonatomic) UILabel *rightBottomLabel;

@end
@implementation SISSPriceTrendChart

- (void)setPriceChartModel:(SISSPriceChartModel *)priceChartModel {
    _priceChartModel = priceChartModel;
    
    self.lineChartView.xAxis.valueFormatter = [[SISSDateValueFormatter alloc] initWithArr:priceChartModel.sellPriceChart.x];
    CGFloat maxPrice = [[priceChartModel.sellPriceChart.y valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat minPrice = [[priceChartModel.sellPriceChart.y valueForKeyPath:@"@min.floatValue"] floatValue];

    self.lineChartView.leftAxis.axisMaximum = maxPrice;
    self.lineChartView.leftAxis.axisMinimum = minPrice;
    
    CGFloat maxRentPrice = [[priceChartModel.rentPriceChart.y1 valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat minRentPrice = [[priceChartModel.rentPriceChart.y1 valueForKeyPath:@"@min.floatValue"] floatValue];
    
    self.lineChartView.rightAxis.axisMaximum = maxRentPrice;
    self.lineChartView.rightAxis.axisMinimum = minRentPrice;
    
    self.leftBottomLabel.text = priceChartModel.sellPriceChart.sellPriceChartList.firstObject.title;
    self.rightBottomLabel.text = priceChartModel.rentPriceChart.title;
    
    [self updateChartData];
}

#pragma mark - 更新图表数据
- (void)updateChartData {
    
    //对应Y轴上面需要显示的数据
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    
    NSArray *sellPointArr = self.priceChartModel.sellPriceChart.sellPriceChartList.firstObject.point;
    NSMutableArray *yArr1 = [NSMutableArray array];
    for (NSString *point in sellPointArr) {
        [yArr1 addObject:[point componentsSeparatedByString:@","].lastObject];
    }
    for (int i = 0; i < yArr1.count; i++) {
        int a = [yArr1[i] intValue];
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:a];
        [yVals1 addObject:entry];
    }
    
    NSMutableArray *yVals2 = [[NSMutableArray alloc] init];
    NSArray *rentPointArr = self.priceChartModel.rentPriceChart.point;
    NSMutableArray *yArr2 = [NSMutableArray array];
    for (NSString *point in rentPointArr) {
        [yArr2 addObject:[point componentsSeparatedByString:@","].lastObject];
    }
    for (int i = 0; i <  yArr2.count; i++) {
        int a = [yArr2[i] intValue];
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:a];
        [yVals2 addObject:entry];
    }
    
    NSArray *sellColorArr = [self.priceChartModel.sellPriceChart.sellPriceChartList.firstObject.color componentsSeparatedByString:@","];
    UIColor *sellColor;
    if (sellColorArr.count == 3) {
        sellColor = [UIColor colorWithRed:[sellColorArr[0] floatValue]/255.f green:[sellColorArr[1] floatValue]/255.f blue:[sellColorArr[2] floatValue]/255.f alpha:1.f];
    }
    
    NSArray *rentColorArr = [self.priceChartModel.rentPriceChart.color componentsSeparatedByString:@","];
    UIColor *rentColor;
    if (rentColorArr.count == 3) {
        rentColor = [UIColor colorWithRed:[rentColorArr[0] floatValue]/255.f green:[rentColorArr[1] floatValue]/255.f blue:[rentColorArr[2] floatValue]/255.f alpha:1.f];
    }
    
    self.leftBottomView.backgroundColor = sellColor;
    self.rightBottomView.backgroundColor = rentColor;
    
    LineChartDataSet *set1 = nil, *set2 = nil;
    
    if (self.lineChartView.data.dataSetCount > 2) {
        set1 = (LineChartDataSet *)self.lineChartView.data.dataSets[0];
        set2 = (LineChartDataSet *)self.lineChartView.data.dataSets[1];
        [set1 replaceEntries:yVals1];
        [set2 replaceEntries:yVals2];
//        set1.values = yVals1;
//        set2.values = yVals2;
        [self.lineChartView.data notifyDataChanged];
        [self.lineChartView notifyDataSetChanged];
    } else {
        set1 = [[LineChartDataSet alloc] initWithEntries:yVals1 label:@"DataSet 1"];
        //自定义set的各种属性
        //设置折线的样式
        set1.drawIconsEnabled = YES;
        set1.formLineWidth = 1.1;//折线宽度
        set1.formSize = 15.0;
        set1.drawValuesEnabled = NO;//是否在拐点处显示数据
        //        set1.valueColors = @[[UIColor blackColor]];//折线拐点处显示数据的颜色
        [set1 setColor:sellColor];//折线颜色
        //折线拐点样式
        set1.drawCirclesEnabled = YES;//是否绘制拐点
        set1.axisDependency = AxisDependencyLeft;
        //        [set1 setColor:[UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f]];
        [set1 setCircleColor:sellColor];
        set1.lineWidth = 2.0;
        set1.circleRadius = 4.0;
        //        set1.fillAlpha = 65/255.0;
        //        set1.fillColor = [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f];
        //        set1.highlightColor = [UIColor colorWithRed:244/255.f green:117/255.f blue:117/255.f alpha:1.f];
        set1.drawCircleHoleEnabled = NO;
        
        set2 = [[LineChartDataSet alloc] initWithEntries:yVals2 label:@"DataSet 2"];
        //自定义set的各种属性
        //设置折线的样式
        set2.drawIconsEnabled = YES;
        set2.formLineWidth = 1.1;//折线宽度
        set2.formSize = 15.0;
        set2.drawValuesEnabled = NO;//是否在拐点处显示数据
        //        [set2 setColor:RGB(248, 144, 28)];//折线颜色
        //折线拐点样式
        set2.drawCirclesEnabled = YES;//是否绘制拐点
        set2.axisDependency = AxisDependencyRight;
        [set2 setColor:rentColor];
        [set2 setCircleColor:rentColor];
        set2.lineWidth = 2.0;
        set2.circleRadius = 4.0;
        //        set2.fillAlpha = 65/255.0;
        //        set2.fillColor = UIColor.redColor;
        //        set2.highlightColor = [UIColor colorWithRed:244/255.f green:117/255.f blue:117/255.f alpha:1.f];
        set2.drawCircleHoleEnabled = NO;
        
        
        NSMutableArray *dataSets = [[NSMutableArray alloc] init];
        [dataSets addObject:set1];
        
        [dataSets addObject:set2];
        
        LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
        
        [data setValueTextColor:UIColor.redColor]; // 文字颜色
        [data setValueFont:[UIFont systemFontOfSize:9.f]]; // 文字字体
        
        self.lineChartView.data = data;
        
        //这里可以调用一个加载动画即1s出来一个绘制点
        //        [self.lineChartView animateWithXAxisDuration:1.0f];
    }
}

#pragma mark - UI
- (void)initUI {
    [super initUI];

    SISSTitleView *titleView = [[SISSTitleView alloc] init];
    titleView.titleStr = @"平均售价走势图（由房谱大数据提供）";
    titleView.titleColor = MAIN_TEXT_COLOR;
    [self addSubview:titleView];
    self.titleView = titleView;
    
    UILabel *leftUnitLabel = [UILabel yyr_labelWithText:@"售价(元/㎡)" fontSize:11 textColor:MAIN_TEXT_COLOR];
    
    [self addSubview:leftUnitLabel];
    self.leftUnitLabel = leftUnitLabel;
    
    UILabel *rightUnitLabel = [UILabel yyr_labelWithText:@"租金(元/月/㎡)" fontSize:11 textColor:MAIN_TEXT_COLOR];
    
    [self addSubview:rightUnitLabel];
    self.rightUnitLabel = rightUnitLabel;

    // 创建折线图
    self.lineChartView = [[LineChartView alloc] init];
    self.lineChartView.legend.form = ChartLegendFormNone; //说明图标
    self.lineChartView.dragEnabled = NO; // 拖动手势
    self.lineChartView.pinchZoomEnabled = NO; //捏合手势
    self.lineChartView.rightAxis.enabled = YES;// 显示右Y轴
    self.lineChartView.chartDescription.enabled = NO; //不显示描述label
    self.lineChartView.doubleTapToZoomEnabled = NO; //禁止双击缩放
    self.lineChartView.drawGridBackgroundEnabled = NO;
    self.lineChartView.drawBordersEnabled = NO;

    //    [self.lineChartView animateWithXAxisDuration:0.01]; //加载动画时长
    [self addSubview:self.lineChartView];

//    self.lineChartView.chartDescription.enabled = YES;
//    self.lineChartView.chartDescription.text = @"dlgjgjj";
    self.lineChartView.legend.enabled = YES;

    ChartLegend *legend = self.lineChartView.legend;
    legend.form = ChartLegendFormNone;

    legend.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:11.f];
    legend.textColor = UIColor.whiteColor;
    legend.horizontalAlignment = ChartLegendHorizontalAlignmentLeft;
    legend.verticalAlignment = ChartLegendVerticalAlignmentBottom;
    legend.orientation = ChartLegendOrientationHorizontal;
    legend.drawInside = NO;

    ChartXAxis *xAxis = self.lineChartView.xAxis;
    xAxis.labelFont = [UIFont systemFontOfSize:8.f];
    xAxis.labelTextColor = UIColor.blackColor;
    xAxis.drawGridLinesEnabled = NO;
    xAxis.drawAxisLineEnabled = NO;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    // 设置左右两边有间隙
    xAxis.granularity = 1.0;
    xAxis.spaceMin = xAxis.granularity / 2;
    xAxis.spaceMax = xAxis.granularity / 2;
    //X轴上面需要显示的数据
//    NSMutableArray *xVals = [[NSMutableArray alloc] init];
//
//    for (int i = 1; i <= 6; i++) {
//        [xVals addObject: [NSString stringWithFormat:@"2018-%d",i]];
//    }
//    xAxis.valueFormatter = [[SISSDateValueFormatter alloc] initWithArr:xVals];

    ChartYAxis *leftAxis = self.lineChartView.leftAxis;
    leftAxis.axisLineColor = UIColor.whiteColor;
    leftAxis.labelTextColor = MAIN_TEXT_COLOR;
    leftAxis.labelFont = [UIFont systemFontOfSize:8];
    leftAxis.axisMaximum = 92000;
    leftAxis.axisMinimum = 46000;
    leftAxis.forceLabelsEnabled = YES;// 强制绘制指定数量的label
    leftAxis.drawGridLinesEnabled = YES;
    leftAxis.drawZeroLineEnabled = NO;
    leftAxis.granularityEnabled = YES;
    //    leftAxis.entries = @[@46000, @55200, @64400, @73600, @82800, @92000];
    //    [leftAxis calculateWithMin:32000 max:35000];

    ChartYAxis *rightAxis = self.lineChartView.rightAxis;
    rightAxis.axisLineColor = UIColor.whiteColor;
    rightAxis.labelTextColor = MAIN_TEXT_COLOR;
    rightAxis.labelFont = [UIFont systemFontOfSize:8];
    rightAxis.axisMaximum = 80;
    rightAxis.axisMinimum = 65;
    rightAxis.drawGridLinesEnabled = NO;
    rightAxis.granularityEnabled = NO;
    rightAxis.forceLabelsEnabled = YES;// 强制绘制指定数量的label
    
    
    UIView *leftBottomView = [[UIView alloc] init];
    leftBottomView.layer.cornerRadius = 2;
    leftBottomView.layer.masksToBounds = YES;
    [self addSubview:leftBottomView];
    self.leftBottomView = leftBottomView;
    UILabel *leftBottomLabel = [UILabel yyr_labelWithText:@"售价" fontSize:15 textColor:MAIN_TEXT_COLOR];
    [self addSubview:leftBottomLabel];
    self.leftBottomLabel = leftBottomLabel;
    
    UIView *rightBottomView = [[UIView alloc] init];
    rightBottomView.layer.cornerRadius = 2;
    rightBottomView.layer.masksToBounds = YES;
    [self addSubview:rightBottomView];
    self.rightBottomView = rightBottomView;
    
    UILabel *rightBottomLabel = [UILabel yyr_labelWithText:@"租金" fontSize:15 textColor:MAIN_TEXT_COLOR];
    [self addSubview:rightBottomLabel];
    self.rightBottomLabel = rightBottomLabel;
    
//    [self updateChartData];
}

- (void)initConstraint {
    [super initConstraint];
    
    CGFloat margin = 8.0;
    WeakSelf
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf);
        make.height.mas_equalTo(5.5 * margin);
    }];
    
    [self.leftUnitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.titleView.mas_bottom).offset(margin);
        make.left.equalTo(weakSelf).offset(margin);
    }];
    
    [self.rightUnitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.leftUnitLabel);
        make.right.equalTo(weakSelf).offset(-margin);
    }];
    
    [self.lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.leftUnitLabel.mas_bottom).offset(margin);
        make.left.right.equalTo(weakSelf);
        make.height.mas_equalTo(200);
    }];
   
    [self.rightBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.leftBottomLabel);
        make.left.equalTo(weakSelf.mas_centerX).offset(2 * margin);
        make.size.mas_equalTo(CGSizeMake(12, 6));
    }];
    
    [self.rightBottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.rightBottomView.mas_right).offset(0.2 * margin);
        make.centerY.equalTo(weakSelf.leftBottomView);
    }];
    
    [self.leftBottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.lineChartView.mas_bottom);
        make.right.equalTo(weakSelf.mas_centerX).offset(-2 * margin);
        make.bottom.equalTo(weakSelf).offset(-2 * margin);
    }];
    
    [self.leftBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.leftBottomLabel.mas_left).offset(-0.2 * margin);
        make.centerY.equalTo(weakSelf.leftBottomLabel);
        make.size.mas_equalTo(CGSizeMake(12, 6));
    }];
    
}


@end
